package fl.ass.service.api;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.IPriorityApiService;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.user.facade.system.dto.SysUsrDatAuthRDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.constant.CapitalConstant;
import com.google.common.collect.Lists;
import fl.ass.facade.api.IAssDealCarApi;
import fl.ass.facade.condition.AssDealCarCostQueryCondition;
import fl.ass.facade.condition.AssDealCarQueryCondition;
import fl.ass.facade.constant.AssTransferInfoEnum;
import fl.ass.facade.constant.DealCarFlowEnum;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.AssDealCarCostDTO;
import fl.ass.facade.dto.AssDealCarDTO;
import fl.ass.facade.dto.AssDealCarTransferDTO;
import fl.ass.facade.dto.AssTransferInfoDTO;
import fl.ass.facade.dto.MessageDTO;
import fl.ass.service.po.AssDealCar;
import fl.ass.service.service.IAssDealCarCostService;
import fl.ass.service.service.IAssDealCarService;
import fl.ass.service.service.IAssTransferInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;
import java.util.Map;

/**
 * 处置转优车API
 * @author zy
 *
 */
@Component
public class AssDealCarApi implements IAssDealCarApi {
	
	private static final Logger logger = LoggerFactory.getLogger(AssDealCarApi.class);
	
	@Autowired
	private IAssDealCarService assDealCarService;
	
	@Autowired
	private IAssDealCarCostService assDealCarCostService;
	
	/**
	 * 权限服务层BEAN
	 */
	@Autowired
	private IPriorityApiService priorityApiService;

    @Autowired
    private ISysUsrApiService sysUsrApiService;//系统用户API 暴露服务

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Autowired
    private IAssTransferInfoService assTransferInfoService;

    @Autowired
    private DataSourceTransactionManager txManager;
	/* (non-Javadoc)
	 * @see fl.ass.facade.api.IAssDealCarApi#saveAssDealCar(fl.ass.facade.dto.AssDealCarDTO)
	 */
	@Override
	public MessageDTO<String> saveAssDealCar(AssDealCarDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		if(null == dto){
			response.setMessage("parameter：dto is can not be null");
		}
		try {
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            // 事物隔离级别，开启新事务
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 获得事务状态
            TransactionStatus status = txManager.getTransaction(def);
			Long id = assDealCarService.saveAssDealCar(dto);
            // 提交事务
            txManager.commit(status);
			response.setId(id);
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}

	/* (non-Javadoc)
	 * @see fl.ass.facade.api.IAssDealCarApi#updateAssDealCar(fl.ass.facade.dto.AssDealCarDTO)
	 */
	@Override
	public MessageDTO<String> updateAssDealCar(AssDealCarDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		if(null == dto){
			response.setMessage("parameter：dto is can not be null");
		}
		try {
			assDealCarService.modify(dto);
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}

	/* (non-Javadoc)
	 * @see fl.ass.facade.api.IAssDealCarApi#findAssDealCarById(java.lang.Long)
	 */
	@Override
	public MessageDTO<AssDealCarDTO> findAssDealCarById(Long id) {
		MessageDTO<AssDealCarDTO> response = new MessageDTO<AssDealCarDTO>();
		if(null == id){
			response.setMessage("parameter：id is can not be null");
		}
		try {
			AssDealCarDTO dto = assDealCarService.selectById(id);
            if(null != dto){
                //获取用户
                if(StringUtils.isNotEmpty(dto.getManageId())){
                    SysUsrDTO usr = this.sysUsrApiService.selectSysUsrById(Long.valueOf(dto.getManageId()), "11000", "0000");
                    String assManagers = usr.getRefRlNm()+"["+usr.getUsrNm()+"]";
                    dto.setManageNm(assManagers);
                }
            }
			if(null != dto){
				response.setData(dto);
			}
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}

	/* (non-Javadoc)
	 * @see fl.ass.facade.api.IAssDealCarApi#findAssDealCarListByPage(cmm.mid.core.framework.page.Pager)
	 */
	@Override
	public Pager findAssDealCarListByPage(Pager page) {
		AssDealCarQueryCondition condition = (AssDealCarQueryCondition)page.getCondition();
		if(null != condition){
			//数据权限控制
			if(null != condition.getUsrId() && StringUtils.isNotBlank(condition.getSysCd())){
				try {
					//需要权限
					List<SysUsrDatAuthRDTO> usrDatAuthRList = this.priorityApiService.searchSysUsrDatAuthRWithOrgCdList(condition.getUsrId(),null,condition.getSysCd());
			        if(CollectionUtils.isNotEmpty(usrDatAuthRList)){
			        	condition.setUsrDatAuthRList(usrDatAuthRList);
					}
				} catch (Exception e) {
                    BaseLogUtils.newLogger("获取用户数据权限失败").setThrowable(e).info();
				}
			}
		}
		return assDealCarService.findAssDealCarListByPage(page);
	}
	/* 
	 * 保存（处置-转优车费用信息表） 
	 */
	@Override
	public MessageDTO<String> saveASSDealCarCost(AssDealCarCostDTO dto) {
		MessageDTO<String> response = new MessageDTO<String>();
		if(null == dto){
			response.setMessage("parameter：dto is can not be null");
		}
		try {
			Long id = assDealCarCostService.add(dto);
			response.setId(id);
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}
	/* 
	 * 分页查询（处置-转优车费用信息表）
	 */
	@Override
	public Pager findAssDealCarCostListByPage(Pager page) {
		return assDealCarCostService.findAssDealCarCostListByPage(page);
	}
	/* 
	 * 删除（处置-转优车费用信息表） 
	 */
	@Override
	public MessageDTO<String> removeById(Long id) throws BaseException {
		MessageDTO<String> response = new MessageDTO<String>();
		if(null == id){
			response.setMessage("parameter：idis can not be null");
		}
		try {
			assDealCarCostService.removeById(id);
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}
	/* 
	 * 修改（处置-转优车费用信息表） 
	 */
	@Override
	public MessageDTO<String> modifyAssDealCarCost(AssDealCarCostDTO dto)
			throws BaseException {
		MessageDTO<String> response = new MessageDTO<String>();
		if(null == dto){
			response.setMessage("parameter：dto is can not be null");
		}
		try {
			this.assDealCarCostService.modify(dto);
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}
	/* 
	 * 查询（处置-转优车费用信息表） 
	 */
	@Override
	public MessageDTO<AssDealCarCostDTO> selectAssDealCarCostById(Long id)
			throws BaseException {
		MessageDTO<AssDealCarCostDTO> response = new MessageDTO<AssDealCarCostDTO>();
		if(null == id){
			response.setMessage("parameter：id is can not be null");
		}
		try {
			AssDealCarCostDTO dto = assDealCarCostService.selectAssDealCarCostById(id);
			if(null != dto){
				response.setData(dto);
			}
			response.setSuccess(true);
		} catch (Exception e) {
            BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public MessageDTO<AssDealCarDTO> searchList(
			AssDealCarQueryCondition condition) throws BaseException {
		MessageDTO<AssDealCarDTO> response = new MessageDTO<AssDealCarDTO>();
		if (null == condition.getDetailId() && null == condition.getMasterId()) {
			response.setMessage("parameter：ids is can not be null");
		}
		try {
			List<AssDealCarDTO> dtos = assDealCarService.searchList(condition);
			if (null != dtos) {
				response.setDatas(dtos);
			}
			response.setSuccess(true);
		} catch (Exception e) {
			BaseLogUtils.newLogger("异常!" + e.getMessage()).setThrowable(e).info();
			response.setMessage(e.getMessage());
		}
		return response;
	}

	@Override
	public Pager searchUnionListByPage(Pager page) throws BaseException {
		try {
			if (null == page) {
				throw new BaseException(BaseExceptionConstant.COMMON_0001, BaseExceptionConstant.COMMON_0001_NAME);
			}

			// 数据查看权限控制
			// 规则：各事业部省总/大区总、商助仅展示当前所在区域转优车数据；贷后管理人员、优车管理人员可查看所有转优车数据
			AssDealCarQueryCondition condition = null;
			if(null != page.getCondition()){
				condition = (AssDealCarQueryCondition) page.getCondition();
			}else {
				condition = new AssDealCarQueryCondition();
				page.setCondition(condition);
			}
			setDataAuth(condition);

			List<AssDealCar> list = assDealCarService.searchUnionListByPage(page);
			List<AssDealCarTransferDTO> resultList = Lists.newArrayListWithCapacity(list.size());
			if (CollectionUtils.isNotEmpty(list)) {
				// 过户进度
				Map<String, String> scheduleCdMap = this.sysDictionaryApiService.searchGroupToMap(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.ASS_SCHEDULE_CD);
				// 过户项目
				Map<String, String> categoryCdMap = this.sysDictionaryApiService.searchGroupToMap(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.ASS_CATEGORY_CD);
				for (AssDealCar po : list) {
					AssDealCarTransferDTO dto = new AssDealCarTransferDTO();
					BeanUtils.copyProperties(po, dto);
					if (po.getTransferInfo() != null) {
						AssTransferInfoDTO assTransferInfoDTO = new AssTransferInfoDTO();
						BeanUtils.copyProperties(po.getTransferInfo(), assTransferInfoDTO);

						assTransferInfoDTO.setCategoryNm(categoryCdMap.get(assTransferInfoDTO.getCategoryCd()));
						assTransferInfoDTO.setScheduleNm(scheduleCdMap.get(assTransferInfoDTO.getScheduleCd()));

						dto.setAssTransferInfoDTO(assTransferInfoDTO);
					}
					dto.setTaskDefKeyNm(DealCarFlowEnum.getTaskDefKeyNm(dto.getTaskDefKey()));
					resultList.add(dto);
				}
			}
			page.setResultList(resultList);
			return page;
		} catch (BaseException e) {
			BaseLogUtils.newLogger("查询转优车管理列表数据业务异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
			throw e;
		} catch (Exception e) {
			BaseLogUtils.newLogger("查询转优车管理列表数据系统异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
			throw e;
		}
	}

    @Override
    public Pager searchAssTransferInfoList(Pager page) throws BaseException {
	    try {
            if (null == page) {
                throw new BaseException(BaseExceptionConstant.COMMON_0001, BaseExceptionConstant.COMMON_0001_NAME);
            }
            page = this.assTransferInfoService.searchListPage(page);
            List<AssTransferInfoDTO> resultList = (List<AssTransferInfoDTO>) page.getResultList();
            if (CollectionUtils.isNotEmpty(resultList)) {
                // List<AssTransferInfoDTO> dtos = AssTransferInfoTransform.toDTOList(resultList);
                // 过户进度
                Map<String, String> scheduleCdMap = this.sysDictionaryApiService.searchGroupToMap(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.ASS_SCHEDULE_CD);
                // 过户项目
                Map<String, String> categoryCdMap = this.sysDictionaryApiService.searchGroupToMap(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.ASS_CATEGORY_CD);
                for (AssTransferInfoDTO dto : resultList) {
                    dto.setCategoryNm(categoryCdMap.get(dto.getCategoryCd()));
                    dto.setScheduleNm(scheduleCdMap.get(dto.getScheduleCd()));
                }
                page.setResultList(resultList);
            }
            return page;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("查询过户信息列表数据业务异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询过户信息列表数据系统异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    @Override
    public Long addAssTransferInfo(AssTransferInfoDTO dto) throws BaseException {
	    try {
            // 过户项目
            String categoryCd = dto.getCategoryCd();
            // 完成情况
            String completionStatus = dto.getCompletionStatus();
            String schedule = AssTransferInfoEnum.getSchedule(categoryCd, completionStatus);
            dto.setScheduleCd(schedule);
            AssDealCarDTO assDealCarDTO = this.assDealCarService.selectById(dto.getDealId());
            if (null == assDealCarDTO) {
                throw new BaseException("根据转优车id查不到数据");
            }
            dto.setPaySchId(assDealCarDTO.getPaySchId());
            dto.setPaySchNo(assDealCarDTO.getPaySchNo());
            dto.setCstId(assDealCarDTO.getCstId());
            dto.setCstNm(assDealCarDTO.getCstNm());
            return assTransferInfoService.add(dto);
        } catch (BaseException e) {
            BaseLogUtils.newLogger("新增过户信息数据业务异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("新增过户信息数据业务异常！").setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    @Override
    public void autoEndDealCarFlow() throws BaseException {
        this.assDealCarService.autoEndDealCarFlow();
    }

    @Override
    public List<AssDealCarCostDTO> searchAssDealCarCostList(AssDealCarCostQueryCondition qc) throws BaseException {
        return this.assDealCarCostService.searchList(qc);
    }

	private void setDataAuth(AssDealCarQueryCondition condition) throws BaseException {
		if (null != condition && condition.getUsrId() != null) {
			StringBuilder bf = new StringBuilder();
			List<SysUsrDatAuthRDTO> list = this.priorityApiService.searchSysUsrDatAuthRWithOrgCdList(condition.getUsrId(), null, condition.getSysCd());
			if (CollectionUtils.isEmpty(list)) {
				bf.append(" AND PB.CST_MGR_ID=" + condition.getUsrId());
			} else {
				boolean flag = false;
				for (SysUsrDatAuthRDTO dto : list) {
					String orgCd = dto.getOrgCd();
					if (StringUtils.isEmpty(orgCd)) {
						continue;
					}
					if (CapitalConstant.SYSORG.equals(orgCd)) {
						return;
					}
					if (bf.length() > 0 && flag) {
						bf.append(" OR ");
					}
					flag = true;
					if (dto.getIsChg() == 1) {//是否主管 1.是 0.否
						bf.append(" PB.CST_MGR_ORG_CD LIKE '" + orgCd + "'||'%' ");
					} else {
						bf.append(" PB.CST_MGR_ORG_CD LIKE '" + orgCd + "'||'_%' ");
					}
				}
				if (StringUtils.isNotEmpty(bf.toString())) {
					bf.insert(0, "AND (((");
					bf.append(") AND PB.CST_MGR_ID != " + condition.getUsrId() + ") OR PB.CST_MGR_ID = " + condition.getUsrId() + ") ");
				}
			}
			condition.setAccessCtrl(bf.toString());
		}
	}

    @Override
    public int modify4Null(AssDealCarDTO entity) throws BaseException {
        return this.assDealCarService.modify4Null(entity);
    }
}
